﻿using System;
using System.ComponentModel;
using System.Globalization;

namespace Gmantis.Controls
{
    public class CharConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (!sourceType.IsAssignableFrom(typeof(string)))
            {
                return sourceType.IsAssignableFrom(typeof(char));
            }
            return true;
        }

        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType.IsAssignableFrom(typeof(char));
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value != null)
            {
                string str = value.ToString();
                if (str.Length > 0)
                {
                    return str[0];
                }
            }
            return null;
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if ((value != null) && destinationType.IsAssignableFrom(typeof(string)))
            {
                return value.ToString();
            }
            return null;
        }
    }
}
